import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/base/base_controller.dart';
import 'package:sports_new/controller/match/list/lq_end_logic.dart';
import 'package:sports_new/controller/match/list/lq_focus_logic.dart';
import 'package:sports_new/controller/match/list/lq_match_filter_logic.dart';
import 'package:sports_new/controller/match/list/lq_notbegin_logic.dart';
import 'package:sports_new/controller/match/list/lq_view_logic.dart';
import 'package:sports_new/controller/match/list/zq_end_logic.dart';
import 'package:sports_new/controller/match/list/zq_focus_logic.dart';
import 'package:sports_new/controller/match/list/zq_match_filter_logic.dart';
import 'package:sports_new/controller/match/list/zq_notbegin_logic.dart';
import 'package:sports_new/controller/match/list/zq_view_logic.dart';
import 'package:sports_new/entity/match/zq_list_entity.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/server/api/other_api.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/match/basketball/lq_all_view.dart';
import 'package:sports_new/view/match/basketball/lq_begin_view.dart';
import 'package:sports_new/view/match/basketball/lq_end_view.dart';
import 'package:sports_new/view/match/basketball/lq_focus_view.dart';
import 'package:sports_new/view/match/basketball/lq_notbegin_view.dart';
import 'package:sports_new/view/match/soccer/zq_hot_view.dart';

import '../../../view/match/basketball/lq_hot_view.dart';
import '../../../view/match/soccer/zq_all_view.dart';
import '../../../view/match/soccer/zq_begin_view.dart';
import '../../../view/match/soccer/zq_end_view.dart';
import '../../../view/match/soccer/zq_focus_view.dart';
import '../../../view/match/soccer/zq_notbegin_view.dart';

enum QuickFilter { all, yiji, jingcai, qingbao, guandian}

extension QuickFilterExtension on QuickFilter {
  String convertString(int type) {
    if (this == QuickFilter.yiji) {
      return "一级";
    } else if (this == QuickFilter.jingcai) {
      return type == 0 ? '竞足' : '竞篮';
    }else if(this == QuickFilter.guandian){
      return "方案";
    } else if (this == QuickFilter.qingbao) {
      return "爆料";
    }
    return "全部";
  }
}

abstract class MatchListProvider {
  Future getMatch();
  Future doRefresh();
  updateView();
  String getTicketName(ZqListEntity match);
}

class MatchPageLogic extends BaseController with GetTickerProviderStateMixin {
  late TabController zqC;
  late TabController lqC;
  List<String> zqTabs = [
    '关注',
    '全部',
    '进行中',
    '赛程',
    '赛果',
  ];
  List<String> lqTabs = [
    '关注',
    '全部',
    '进行中',
    '赛程',
    '赛果',
  ];
  List<String> zqTags = [
    Constant.matchFilterTagFocus,
    Constant.matchFilterTagAll,
    Constant.matchFilterTagBegin,
    Constant.matchFilterTagSchedule,
    Constant.matchFilterTagResult,
  ];
  List<String> lqTags = [
    Constant.matchFilterTagFocus,
    Constant.matchFilterTagAll,
    Constant.matchFilterTagBegin,
    Constant.matchFilterTagSchedule,
    Constant.matchFilterTagResult,
  ];
  List<Widget> zqPages = [
    const ZqFocusView(),
    const ZqAllView(),
    const ZqBeginView(),
    const ZqNotBeginView(),
    const ZqEndView(),
  ];
  List<Widget> lqPages = [
    const LqFocusView(),
    const LqAllView(),
    const LqBeginView(),
    const LqNotBeginView(),
    const LqEndView(),
  ];
  int headIndex = 0;
  int soccerIndex = 0;
  int basketIndex = 0;
  final _opacity = (1.0).obs;
  bool _isLoading = true;

  bool get isLoading => _isLoading;

  set isLoading(bool value) {
    _isLoading = value;
    update();
  }
  // ScrollController scrollC = ApmScrollController();
  // final GlobalKey<ExtendedNestedScrollViewState> key =
  //     GlobalKey<ExtendedNestedScrollViewState>();

  @override
  void onInit() async{
    super.onInit();
    try {
      Get.put(ZqMatchFilterLogic(), tag: Constant.matchFilterTagFocus,permanent: true);
      Get.put(ZqMatchFilterLogic(), tag: Constant.matchFilterTagAll,permanent: true);
      Get.put(ZqMatchFilterLogic(), tag: Constant.matchFilterTagBegin,permanent: true);
      Get.put(ZqMatchFilterLogic(), tag: Constant.matchFilterTagSchedule,permanent: true);
      Get.put(ZqMatchFilterLogic(), tag: Constant.matchFilterTagResult,permanent: true);
      Get.put(LqMatchFilterLogic(), tag: Constant.matchFilterTagFocus,permanent: true);
      Get.put(LqMatchFilterLogic(), tag: Constant.matchFilterTagAll,permanent: true);
      Get.put(LqMatchFilterLogic(), tag: Constant.matchFilterTagBegin,permanent: true);
      Get.put(LqMatchFilterLogic(), tag: Constant.matchFilterTagSchedule,permanent: true);
      Get.put(LqMatchFilterLogic(), tag: Constant.matchFilterTagResult,permanent: true);
    }catch(e){
      log(e.toString());
    }
    try{
      await getHotLabel();
    }catch(e){
      log(e.toString());
    }
    zqC = TabController(
        length: zqTabs.length, vsync: this, initialIndex: soccerIndex);
    lqC = TabController(
        length: lqTabs.length, vsync: this, initialIndex: basketIndex);
    isLoading = false;
    update();
    // scrollC.addListener(() {
    //   configOpacity();
    // });
    zqC.addListener(() {
      changeTab(zqC.index);
    });
    lqC.addListener(() {
      changeTab(lqC.index);
    });
    Future.delayed(const Duration(milliseconds: 200)).then((value) => showGuide());
  }

  double get opacity {
    if (_opacity < 0) {
      return 0.0;
    } else if (_opacity > 1) {
      return 1.0;
    } else {
      return _opacity.value;
    }
  }

  Future getHotLabel() async{
    List<ResourceEntity>? zq = await OtherApi.getAppList("match_head_zq");
    List<ResourceEntity>? lq = await OtherApi.getAppList("match_head_lq");

    List<String>? zqHotTab = zq?.map((e) => e.imgUrl?.isNotEmpty == true?e.imgUrl!:e.title ?? "").toList();
    List<String>? lqHotTab = lq?.map((e) => e.imgUrl?.isNotEmpty == true?e.imgUrl!:e.title ?? "").toList();
    List<String>? zqHotId = zq?.map((e) => [e.content??"",if(e.button.hasValue)e.button??""].join("-")).toList();
    List<String>? lqHotId = lq?.map((e) => [e.content??"",if(e.button.hasValue)e.button??""].join("-")).toList();
    if(zqHotTab?.isNotEmpty ==true) {
      zqTabs = zqTabs.insertWith(1, zqHotTab!);
      zqPages = zqPages.insertWith(
        1, List.generate(zqHotTab.length, (index) => ZqHotView(hotId: zqHotId?[index] ?? "", title: zqHotTab[index])));
      zqTags = zqTags.insertWith(1, zqHotTab.map((e) => "${Constant.matchFilterTagHot}$e"));
      for (var element in zqHotTab) {
        Get.put(ZqMatchFilterLogic(hotLabel: element), tag: "${Constant.matchFilterTagHot}$element",permanent: true);
      }
    }
    if(lqHotTab?.isNotEmpty ==true) {
      lqTabs = lqTabs.insertWith(1, lqHotTab!);
      lqPages = lqPages.insertWith(
        1, List.generate(lqHotTab.length, (index) => LqHotView(hotId: lqHotId?[index] ?? "", title: lqHotTab[index])));
      lqTags = lqTags.insertWith(1, lqHotTab.map((e) => "${Constant.matchFilterTagHot}$e"));
      for (var element in lqHotTab) {
        Get.put(LqMatchFilterLogic(hotLabel: element), tag: "${Constant.matchFilterTagHot}$element",permanent: true);
      }
    }
    int zqDefault = zq!.indexWhere((element) => element.extInfo == "1");
    int lqDefault = lq!.indexWhere((element) => element.extInfo == "1");
    if(zqDefault != -1){
      soccerIndex = zqDefault+1;
      Get.put(
          ZqViewLogic(ZqMatchType.all, Constant.matchFilterTagAll),
          tag: Constant.matchFilterTagAll,permanent: true
      );
    }else{
      soccerIndex = zqTabs.indexOf("全部");
    }
    if(lqDefault != -1){
      basketIndex = zqDefault+1;
      Get.put(
          LqViewLogic(LqMatchType.all, Constant.matchFilterTagAll),
          tag: Constant.matchFilterTagAll,permanent: true
      );
    }else{
      basketIndex = lqTabs.indexOf("全部");
    }
  }

  changeTab(int index) {
    if (headIndex == 0) {
      soccerIndex = index;
    } else {
      basketIndex = index;
    }
    update();
  }

  changeMatchTab(String tag) {
    int index = 0;
    if (headIndex == 0) {
      index = zqTags.indexOf(tag);
      zqC.animateTo(index);
    } else {
      index = lqTags.indexOf(tag);
      lqC.animateTo(index);
    }
    changeTab(index);
  }

  MatchListProvider getMatchController() {
    MatchListProvider? logic;
    if (headIndex == 0) {
      if(zqPages[soccerIndex] is ZqHotView){
        logic = Get.find<ZqViewLogic>(tag: "${Constant.matchFilterTagHot}${zqTabs[soccerIndex]}");
      }else if (zqPages[soccerIndex] is ZqAllView) {
        logic = Get.find<ZqViewLogic>(tag: Constant.matchFilterTagAll);
      } else if (zqPages[soccerIndex] is ZqBeginView) {
        logic = Get.find<ZqViewLogic>(tag: Constant.matchFilterTagBegin);
      } else if (zqPages[soccerIndex] is ZqNotBeginView) {
        final index = Get.find<ZqNotBeginLogic>().index;
        logic = Get.find<ZqViewLogic>(
            tag: '${Constant.matchFilterTagSchedule}$index');
      } else if (zqPages[soccerIndex] is ZqEndView) {
        final index = Get.find<ZqEndLogic>().index;
        logic = Get.find<ZqViewLogic>(
            tag: '${Constant.matchFilterTagResult}$index');
      } else if (zqPages[soccerIndex] is ZqFocusView) {
        logic = Get.find<ZqFocusLogic>();
      }
    } else {
      if(lqPages[basketIndex] is LqHotView){
        logic = Get.find<LqViewLogic>(tag: "${Constant.matchFilterTagHot}${lqTabs[basketIndex]}");
      }else if (lqPages[basketIndex] is LqAllView) {
        logic = Get.find<LqViewLogic>(tag: Constant.matchFilterTagAll);
      } else if (lqPages[basketIndex] is LqBeginView) {
        logic = Get.find<LqViewLogic>(tag: Constant.matchFilterTagBegin);
      } else if (lqPages[basketIndex] is LqFocusView) {
        logic = Get.find<LqFocusLogic>();
      } else if (lqPages[basketIndex] is LqNotBeginView) {
        final index = Get.find<LqNotBeginLogic>().index;
        logic = Get.find<LqViewLogic>(
            tag: '${Constant.matchFilterTagSchedule}$index');
      } else if (lqPages[basketIndex] is LqEndView) {
        final index = Get.find<LqEndLogic>().index;
        logic = Get.find<LqViewLogic>(
            tag: '${Constant.matchFilterTagResult}$index');
      }
    }

    return logic!;
  }

  showGuide() async {
    if (SpUtils.matchGuide != null) {
      return;
    }
    SpUtils.matchGuide = true;
    await Get.dialog(
      guideWidget(1),
      barrierColor: Colours.transparent,
      useSafeArea: false,
      transitionDuration: const Duration(seconds: 0),
    );
    await Get.dialog(
      guideWidget(2),
      barrierColor: Colours.transparent,
      useSafeArea: false,
      transitionDuration: const Duration(seconds: 0),
    );
  }

  guideWidget(int type) {
    return GestureDetector(
      onTap: () {
        Get.back();
      },
      child: Stack(
        children: [
          Container(
            color: Colours.black.withOpacity(0.8),
          ),
          Positioned(
              left: type == 1 ? 4 : null,
              right: type == 2 ? 4 : null,
              top: MediaQuery.of(Get.context!).padding.top,
              child: Image.asset(
                Utils.getImgPath(
                    type == 1 ? 'match_guide_1.png' : 'match_guide_2.png'),
                width: 292,
                height: 176,
              ))
        ],
      ),
    );
  }

  @override
  void getRefresh() async{
    if(isLoading) return;
    try {
      isLoading = true;
      zqTabs = [
        '关注',
        '全部',
        '进行中',
        '赛程',
        '赛果',
      ];
      lqTabs = [
        '关注',
        '全部',
        '进行中',
        '赛程',
        '赛果',
      ];
      zqTags = [
        Constant.matchFilterTagFocus,
        Constant.matchFilterTagAll,
        Constant.matchFilterTagBegin,
        Constant.matchFilterTagSchedule,
        Constant.matchFilterTagResult,
      ];
      lqTags = [
        Constant.matchFilterTagFocus,
        Constant.matchFilterTagAll,
        Constant.matchFilterTagBegin,
        Constant.matchFilterTagSchedule,
        Constant.matchFilterTagResult,
      ];
      zqPages = [
        const ZqFocusView(),
        const ZqAllView(),
        const ZqBeginView(),
        const ZqNotBeginView(),
        const ZqEndView(),
      ];
      lqPages = [
        const LqFocusView(),
        const LqAllView(),
        const LqBeginView(),
        const LqNotBeginView(),
        const LqEndView(),
      ];
      update();
      try {
        zqC.dispose();
        lqC.dispose();
      }catch(e){
        Logger().d(e);
      }
      try {
        await getHotLabel();
      }catch(e){
        log(e.toString());
      }
      try {
        zqC = TabController(
          length: zqTabs.length, vsync: this, initialIndex: soccerIndex
        );
        lqC = TabController(
          length: lqTabs.length, vsync: this, initialIndex: basketIndex
        );
        zqC.addListener(() {
          changeTab(zqC.index);
        });
        lqC.addListener(() {
          changeTab(lqC.index);
        });
      }catch(e){
        Logger().d(e);
      }
      isLoading = false;
      update();
    }catch(e){
      log(e.toString());
    }
    super.getRefresh();
  }
}
